package com.ok.common.ext

import com.ok.common.utils.ByteArrayToBase64Adapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory

/**
 * json转object
 */
inline fun <reified T> String.jsonToObject(moshi: Moshi = defaultMoshiAdapter): T? {
    return try {
        val adapter = moshi.adapter(T::class.java)
        adapter.fromJson(this)
    } catch (e: Exception) {
        e.printStackTrace()
        null
    }
}

/**
 * json转list
 */
inline fun <reified T> String.jsonToList(moshi: Moshi = defaultMoshiAdapter): List<T> {
    return try {
        val listType = com.squareup.moshi.Types.newParameterizedType(List::class.java, T::class.java)
        val adapter = moshi.adapter<List<T>>(listType)
        adapter.fromJson(this) ?: emptyList()
    } catch (e: Exception) {
        e.printStackTrace()
        emptyList()
    }
}

inline fun <reified T> String.jsonToMutableList(moshi: Moshi = defaultMoshiAdapter): MutableList<T> {
    return try {
        val listType = com.squareup.moshi.Types.newParameterizedType(MutableList::class.java, T::class.java)
        val adapter = moshi.adapter<MutableList<T>>(listType)
        adapter.fromJson(this) ?: mutableListOf()
    } catch (e: Exception) {
        e.printStackTrace()
        mutableListOf()
    }
}

/**
 * object转json
 */
fun Any.toJson(moshi: Moshi = defaultMoshiAdapter): String {
    return try {
        val adapter = moshi.adapter(Any::class.java)
        adapter.toJson(this)
    } catch (e: Exception) {
        e.printStackTrace()
        ""
    }
}

/**
 * 默认转换适配器
 */
val defaultMoshiAdapter: Moshi = Moshi.Builder()
    .add(KotlinJsonAdapterFactory())
    .add(ByteArrayToBase64Adapter())
    .build() 